import {
    DisplaySlotId,
    EntityComponentTypes,
    ItemLockMode,
    ItemStack,
    Player,
    world,
} from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { KcqdProcessController } from "./components/process";
import { kcqdSnatch } from "./components/snatch";
import { KcqdModule } from "./module";
import { KcqdDaemon } from "./components/daemon";
import { KcpdShowDb } from "@/kcpd/moudle";

export class KcqdMainState extends KcqdModule.State {
    readonly sausageItem = new ItemStack("kcpd:sausage");

    override onEnter(): void {
        this.sausageItem.lockMode = ItemLockMode.slot;
        this.addComponent(Timer, {
            initialTime: this.context.config.roundTime,
            autoStart: true,
        });
        this.addComponent(kcqdSnatch)
            .addComponent(KcqdProcessController)
            .addComponent(KcqdDaemon);
        KcpdShowDb.setDisplaySlot(DisplaySlotId.Sidebar);

        this.initPlayers();
    }

    initPlayers() {
        const result = this.getComponent(KcqdProcessController).getSausage();
        if (!result) {
            this.end();
            return;
        }
        this.context.players.forEach((p) => {
            p.player.teleport(this.context.map.spawnPoint);
            p.player.setSpawnPoint({
                ...this.context.map.spawnPoint,
                dimension: Dimensions.Overworld,
            });
            if (p.isSausage) {
                p.title("§c游戏开始", "§b§l保护好你的烤肠");
            } else {
                p.title("§c游戏开始", "§b§l你是猎人，找到所有烤肠！");
            }
        });
    }

    getPlayersWithSauage() {
        return this.context.players.filter(
            (p) => p.isValid && !p.win && p.isSausage
        );
    }

    giveSausage(player: Player) {
        const container = player.getComponent(
            EntityComponentTypes.Inventory
        )?.container;
        if (!container) return;
        for (let i = 0; i < 9; i++) {
            container.setItem(i, this.sausageItem);
        }
    }

    end() {
        this.engine.stopGame();
    }

    override onExit(): void {
        world.scoreboard.clearObjectiveAtDisplaySlot(DisplaySlotId.Sidebar);
    }
}
